// ajax请求数据，使用promise来解决异步请求，封装轮播效果

var ulla = document.querySelectorAll('.ulla')[0];
var olla = document.querySelectorAll('.olla')[0];
var btnArr = document.querySelectorAll('.btnArr')[0];
var container = document.querySelectorAll('.container')[0];
var sBtn = btnArr.children;
var conter = 0;
var timer = null;

container.onmouseover = function() {
    btnArr.style.display = "block";
    clearInterval(timer);
}
container.onmouseout = function() {
    btnArr.style.display = "none";
    timer = setInterval(sBtn[1].onclick, 1500)
}


setAjax('../../mycode/mock/data.json').then((key) => {
    var data = JSON.parse(key);
    var html = '';
    for (var i in data) {
        html += `<li><img src="${data[i].imag}" alt=""></li>`;
    }
    ulla.innerHTML = html;

    var list = ulla.children;
    for (var i = 0; i < list.length; i++) {
        var li = document.createElement('li');
        li.innerHTML += (i + 1)
        olla.appendChild(li)
    }

    var olis = olla.children;
    olis[0].classList.add('current')

    for (var n = 0; n < olis.length; n++) {
        olis[n].index = n;
        olis[n].onclick = function() {
            for (var j = 0; j < olis.length; j++) {
                olis[j].classList.remove('current')
                list[j].style.display = 'none';
            }
            olis[this.index].classList.add('current')
            list[this.index].style.display = 'block';
            conter = this.index;
        }
    }

    sBtn[0].onclick = function() {
        conter--;
        if (conter < 0) {
            conter = olis.length - 1;
        }
        for (var j = 0; j < olis.length; j++) {
            olis[j].classList.remove('current')
            list[j].style.display = 'none';
        }
        olis[conter].classList.add('current')
        list[conter].style.display = 'block';
    }

    sBtn[1].onclick = function() {
        conter++;
        if (conter > olis.length - 1) {
            conter = 0;
        }
        for (var j = 0; j < olis.length; j++) {
            olis[j].classList.remove('current')
            list[j].style.display = 'none';
        }
        olis[conter].classList.add('current')
        list[conter].style.display = 'block';
    }

    timer = setInterval(sBtn[1].onclick, 1500)
})








function setAjax(url) {
    return new Promise((resolve, reject) => {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url)
        xhr.onreadystatechange = () => {
            if (xhr.readyState != 4) return
            if (xhr.status === 200) {
                resolve(xhr.responseText);
            } else {
                reject(new Error('error'))
            }
        }
        xhr.send(null);
    })
}